﻿using Hwh_Shop.Models.Database;
using Hwh_Shop.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Hwh_Shop.Controllers
{
	/// <summary>
	/// 订单模块
	/// </summary>
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class OrderController : ControllerBase
	{
		// 定义数据库上下文
		private readonly Hwh_ShopContext _db;

		/// <summary>
		/// 构造方法 构造注入
		/// 把数据库上下文初始化
		/// </summary>
		/// <param name="db"></param>
		public OrderController(Hwh_ShopContext db)
		{
			_db = db;
		}

		/// <summary>
		/// 结算
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		[Authorize] //标签 接口需要授权
		public string Balance()
		{
			//获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
			var userTel = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
																												 // 查询用户的购物车
			var shoppingCars = _db.ShoppingCars.Where(x => x.ShopCarUser == userTel).ToList();
			if (shoppingCars.Count == 0)
			{
				return "购物车为空";
			}
			// 获取当前时间戳
			DateTimeOffset dateTimeOffset = DateTimeOffset.UtcNow;
			long unixTimeMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
			string timestamp = unixTimeMilliseconds.ToString();
			foreach (var item in shoppingCars)
			{
				// 查询商品信息
				var commodity = _db.Commodities.Find(item.ComNo);
				if (commodity == null)
				{
					return "商品[" + item.ComNo + "]不存在，请从购物车内移除后重新下单";
				}
				// 查询商品库存
				var stock = _db.Commodities.FirstOrDefault(x => x.ComNo == item.ComNo).ComCount;
				if (stock < item.ShopCarCount)
				{
					return "商品[" + item.ComNo + "]库存不足，数量：" + item.ShopCarCount + " 库存：" + stock;
				}
				// 减少库存
				_db.Commodities.FirstOrDefault(x => x.ComNo == item.ComNo).ComCount -= item.ShopCarCount;
				// 生成订单
				_db.Orders.Add(new Order
				{
					OrderNo = timestamp,
					OrderPrice = commodity.ComPrice * item.ShopCarCount,
					OrderUser = userTel,
					OrderCom = item.ComNo,
					OrderState = "待发货"
				});
				// 生成详细订单
				_db.OrderDetaileds.Add(new OrderDetailed
				{
					OrderNo = timestamp,
					OrderUser = userTel,
					ComName = commodity.ComName,
					ComCateNo = commodity.ComCateNo,
					ComPhoto = commodity.ComPhoto,
					ComPrice = commodity.ComPrice,
					ComRefer = commodity.ComRefer
				});
				// 清空购物车
				_db.ShoppingCars.Remove(item);
			}
			var rows = _db.SaveChanges();
			if (rows == 0)
			{
				return "下单失败";
			}
			else
			{
				return "下单成功";
			}
		}

		/// <summary>
		/// 用户订单列表
		/// </summary>
		/// <param name="OrderState"></param>
		/// <returns></returns>
		[HttpGet]
		[Authorize] //标签 接口需要授权
		public List<Order_OrderList> OrderList(string OrderState)
		{
			//获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
			var userTel = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号
																												 // 查询用户所有的订单号，去重
			var orderNos = _db.Orders.Where(x => x.OrderUser == userTel).Select(x => x.OrderNo).Distinct().ToList();


			if (OrderState != "待发货" && OrderState != "待收货" && OrderState != null)
			{
				List<Order_OrderList> order_OrderLists_Errmsg = new List<Order_OrderList>();
				order_OrderLists_Errmsg.Add(new Order_OrderList
				{
					OrderNo = null,
					OrderPrice = 0,
					OrderState = "订单状态输入错误"
				});
				return order_OrderLists_Errmsg;
			}

			if (OrderState != null)
			{
				// 查询用户的订单中OrderState状态的所拥有的订单号，去重
				orderNos = _db.Orders.Where(x => x.OrderUser == userTel && x.OrderState == OrderState).Select(x => x.OrderNo).Distinct().ToList();
			}

			if (orderNos.Count == 0)
			{
				List<Order_OrderList> order_OrderLists_Errmsg = new List<Order_OrderList>();
				order_OrderLists_Errmsg.Add(new Order_OrderList
				{
					OrderNo = null,
					OrderPrice = 0,
					OrderState = "暂无订单"
				});
				return order_OrderLists_Errmsg;
			}

			List<Order_OrderList> Order_OrderLists = new List<Order_OrderList>();
			foreach (var item in orderNos)
			{
				// 查询订单的价格
				var orderPrice = _db.Orders.Where(x => x.OrderNo == item).Sum(x => x.OrderPrice);
				// 查询订单的状态
				var orderState = _db.Orders.FirstOrDefault(x => x.OrderNo == item).OrderState;
				Order_OrderLists.Add(new Order_OrderList
				{
					OrderNo = item,
					OrderPrice = orderPrice,
					OrderState = orderState
				});
			}

			return Order_OrderLists;
		}

		/// <summary>
		/// 后台订单列表
		/// </summary>
		/// <returns></returns>
		[HttpGet]
		public List<Order_BackendOrdersList> BackendOrdersList()
		{
			var OrderList = _db.Orders.Select(x => x.OrderNo).Distinct().ToList();
			List<Order_BackendOrdersList> Order_BackendOrdersLists = new List<Order_BackendOrdersList>();
			foreach (var item in OrderList)
			{
				Order_BackendOrdersLists.Add(new Order_BackendOrdersList
				{
					OrderNo = item,
					OrderPrice = _db.Orders.Where(x => x.OrderNo == item).Sum(x => x.OrderPrice),
					OrderUser = _db.Orders.FirstOrDefault(x => x.OrderNo == item).OrderUser,
					OrderCom = _db.Orders.Where(x => x.OrderNo == item).Select(x => x.OrderCom).ToList(),
					OrderState = _db.Orders.FirstOrDefault(x => x.OrderNo == item).OrderState
				});
			}
			return Order_BackendOrdersLists;
		}

		/// <summary>
		/// 发货
		/// </summary>
		/// <param name="order_delivery">分别输入“订单编号”、“快递公司”、“快递单号”</param>
		/// <returns></returns>
		[HttpPost]
		public string Delivery(Order_Delivery order_delivery)
		{
			// 查询订单是否存在
			var order = _db.Orders.FirstOrDefault(x => x.OrderNo == order_delivery.OrderNo);
			if (order == null)
			{
				return "订单不存在";
			}

			if (order_delivery.ExpressDeliveryCompanies == null || order_delivery.OrderDeliveryNo == null)
			{
				return "快递公司或快递单号不能为空";
			}

			// 查询订单状态是否为待发货
			if (order.OrderState == "已发货")
			{
				return "订单已经存在发货记录，不支持再次发货";
			}
			else if (order.OrderState != "待发货")
			{
				return "订单状态错误";
			}

			if (_db.WaybillOfInformations.Find(order_delivery.OrderDeliveryNo) != null)
			{
				return "快递单号已存在，请检查";
			}

			// 获取该订单的商品
			var orderCom = _db.Orders.Where(x => x.OrderNo == order_delivery.OrderNo).ToList();
			foreach (var item in orderCom)
			{
				// 修改订单状态为已发货
				item.OrderState = "已发货";
			}

			// 添加快递信息
			_db.WaybillOfInformations.Add(new WaybillOfInformation
			{
				// 快递单号
				WayInNo = order_delivery.OrderDeliveryNo,
				// 快递公司
				WayInFirm = order_delivery.ExpressDeliveryCompanies,
				// 订单编号
				OrderNo = order_delivery.OrderNo
			});
			var rows = _db.SaveChanges();
			if (rows == 0)
			{
				return "发货失败";
			}
			else
			{
				return "发货成功";
			}


		}
	}
}
